// 首页服务逻辑

import type { User, Article } from './types'

const API_BASE_URL = 'http://localhost:3000/api'

// 获取用户资料
export const fetchProfile = async (): Promise<User> => {
  const token = localStorage.getItem('token')
  const res = await fetch(`${API_BASE_URL}/profile`, {
    headers: token ? { Authorization: `Bearer ${token}` } : {}
  })
  
  if (res.ok) {
    const response = await res.json()
    return response.data || {}
  }
  
  return {}
}

// 获取文章列表
export const fetchArticles = async (): Promise<Article[]> => {
  const token = localStorage.getItem('token')
  const res = await fetch(`${API_BASE_URL}/articles`, {
    headers: token ? { Authorization: `Bearer ${token}` } : {}
  })
  
  if (res.ok) {
    const response = await res.json()
    return response.data || []
  }
  
  return []
}

// 格式化日期
export const formatDate = (dateString: string | undefined): string => {
  if (!dateString) return '未知日期'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

// 获取封面图片URL
export const getCoverUrl = (url?: string): string => {
  if (!url) return 'https://picsum.photos/800/400?random=default'
  if (/^https?:/.test(url)) return url
  return `${API_BASE_URL}${url}`
}

// 处理图片加载错误
export const onImgError = (e: Event): void => {
  const target = e.target as HTMLImageElement
  if (target) target.src = 'https://picsum.photos/800/400?random=default'
} 